# 462 中等：最少移动次数使数组元素相等II

def minMoves2(nums):
    # 平均数
    # avg = sum(nums) // len(nums)
    # ret = 0
    # for num in nums:
    #     ret += abs(avg - num)
    # return ret

    # 中位数
    nums = sorted(nums)
    if len(nums) % 2 == 1:
        mid = nums[len(nums)//2]
    else:
        mid = int((nums[len(nums)//2] + nums[len(nums)//2-1])/2)
    ret = 0
    for num in nums:
        ret += abs(num - mid)
    return ret
